﻿using JYH.Data;
using JYH.Framework;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace JYH.DataAccess
{
   public  class HardWareRegist
    {
        public static bool RegistHardWare(string Key, string Code, string ConnString, string ConnType, string US, out string Msg)
        {
            bool result = false;
            Database MyDB = new Database(ConnString, ConnType);
            Msg = string.Empty;
            MyDB.BeginTransaction();
            try
            {

                if (!string.IsNullOrEmpty(Key))
                {
                    string HwInfo = Security.DESEncrypt(Key);
                    string CodeInfo = Security.DESDecrypt(Code, Key);
                    string Hw = string.Empty;
                    string LimitDate = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
                    string LastDate = DateTime.Now.ToString("yyyyMMdd");
                    string us = Security.DESEncrypt(US);
                    string[] ListMsg = CodeInfo.Split('|');
                    if (ListMsg.Length > 2)
                    {
                        Hw = ListMsg[1].ToString();
                        LimitDate = ListMsg[0].ToString();
                    }

                    IFormatProvider provider = new CultureInfo("zh-CN", true);
                    DateTime dtLimit = DateTime.ParseExact(LimitDate, "yyyyMMdd", provider); //有效日期
                    DateTime dtLast = DateTime.ParseExact(LastDate, "yyyyMMdd", provider);
                    if (dtLimit <= dtLast)
                    {
                        Msg = " Regist Faile";
                        return false;
                    }
                    if (Hardware.CheckHardWare(Hw))
                    {
                        HwInfo = Security.DESEncrypt(Key);
                        LimitDate = Security.DESEncrypt(LimitDate);
                        LastDate = Security.DESEncrypt(LastDate);
                        string sql = "Select  HwInfo,LimitDate,LastDate,LastHw From SysConfig Where HwInfo='" + HwInfo + "'";
                        DataTable dt = new DataTable();
                        MyDB.Fill(dt, sql, null);
                        if (dt == null)
                        {
                            Msg = " Regist Faile";
                            return false;
                        }
                        if (dt.Rows.Count > 1)
                        {
                            sql = "Delete SysConfig";
                            MyDB.Execute(sql, null);
                            Msg = " Regist Faile";
                            return false;
                        }
                        if (dt.Rows.Count == 0)
                        {
                            sql = @"Insert Into SysConfig (HwInfo,LimitDate,LastDate,LastHw)
                                    values ('" + HwInfo + "','" + LimitDate + "','" + LastDate + "','" + us + "')";
                        }
                        if (dt.Rows.Count == 1)
                        {
                            sql = @"Update SysConfig Set LimitDate='" + LimitDate + "',LastDate='" + LastDate + "',LastHw='" + us + "' Where HwInfo='" + HwInfo + "'";
                        }
                        MyDB.Execute(sql, null);

                    }

                }
                result = true;
                MyDB.CompleteTransaction();
            }
            catch (Exception ex)
            {
                Msg = ex.ToString();
                MyDB.AbortTransaction();
                return false;
            }
            return result;
        }


        public static void RegistDB(IniFileHelp IniHelp)
        {


            string Msg = string.Empty;
            string LogName = Application.StartupPath + @"\Log\" + DateTime.Now.ToString("yyyyMMddHHmmss") + "Log.txt";
            try
            {

                string Hw = IniHelp.ReadString("MES", "HW", "");
                if (string.IsNullOrEmpty(Hw))
                {
                    Msg = "硬件信息不存在" + IniHelp.FileName + IniHelp.ToString();
                    File.AppendAllText(LogName, Msg + DateTime.Now.ToString());
                    return;
                }
                Hw = Security.DESDecrypt(Hw);
                string Key = Hw;
                string Code = IniHelp.ReadString("MES", "KEY", "");
                if (string.IsNullOrEmpty(Code))
                {
                    Msg = "产品授权码存在";
                    File.AppendAllText(LogName, Msg + DateTime.Now.ToString());
                    return;
                }
                string US = IniHelp.ReadString("MES", "US", "");
                if (string.IsNullOrEmpty(US))
                {
                    US = "0";
                }
                DataTable dt = JyhDataType.GetJyhDataType();
                string ConnType = IniHelp.ReadString("ASCONN", "DBTYPE", "");
                if (string.IsNullOrEmpty(ConnType))
                {
                    Msg = "请设置数据库";
                    File.AppendAllText(LogName, Msg + DateTime.Now.ToString());
                    return;
                }
                // File.AppendAllText(LogName, ConnType + DateTime.Now.ToString());
                ConnType = Security.DESDecrypt(ConnType);
                string ConnString = string.Empty;
                foreach (DataRow dr in dt.Rows)
                {
                    if (string.Equals(dr["DBTYPE"].ToString(), ConnType))
                    {
                        ConnString = dr["DBCONN"].ToString();

                    }
                }
                string DBSRV = Security.DESDecrypt(IniHelp.ReadString("ASCONN", "DBSRV", ""));
                string DBNAME = Security.DESDecrypt(IniHelp.ReadString("ASCONN", "DBNAME", ""));
                string DBUSER = Security.DESDecrypt(IniHelp.ReadString("ASCONN", "DBUSER", ""));
                string DBPWD = Security.DESDecrypt(IniHelp.ReadString("ASCONN", "DBPWD", ""));
                ConnString = string.Format(ConnString, DBSRV, DBNAME, DBUSER, DBPWD);
                bool result = RegistHardWare(Key, Code, ConnString, ConnType, US, out Msg);
                if (!result)
                    File.AppendAllText(LogName, Msg + DateTime.Now.ToString());
            }
            catch (Exception ex)
            {
                Msg = ex.ToString();
                File.AppendAllText(LogName, Msg + DateTime.Now.ToString());
            }

        }

        public static Database InitDB()
        {
            IniFileHelp IniHelp = new IniFileHelp("");
            Database db = null;
            string DBTYPE = IniHelp.ReadString("DBCONN", "DBTYPE", "");
            if (!string.IsNullOrEmpty(DBTYPE))
            {
                DBTYPE = Security.DESDecrypt(DBTYPE);
            }
            string DBSRV = IniHelp.ReadString("DBCONN", "DBSRV", "");
            if (!string.IsNullOrEmpty(DBSRV))
            {
                DBSRV = Security.DESDecrypt(DBSRV);
            }
            string DBNAME = IniHelp.ReadString("DBCONN", "DBNAME", "");
            if (!string.IsNullOrEmpty(DBNAME))
            {
                DBNAME = Security.DESDecrypt(DBNAME);
            }
            string DBUSER = IniHelp.ReadString("DBCONN", "DBUSER", "");
            if (!string.IsNullOrEmpty(DBUSER))
            {
                DBUSER = Security.DESDecrypt(DBUSER);
            }
            string DBPWD = IniHelp.ReadString("DBCONN", "DBPWD", "");
            if (!string.IsNullOrEmpty(DBPWD))
            {
                DBPWD = Security.DESDecrypt(DBPWD);
            }
            DataTable dt = JyhDataType.GetJyhDataType();
            string DBCONN = string.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                if (string.Equals(dr["DBTYPE"].ToString(), DBTYPE))
                {
                    DBCONN = string.Format(dr["DBCONN"].ToString(), DBSRV, DBNAME, DBUSER, DBPWD);
                }
            }
            db = DB.D(DBCONN, DBTYPE);
            return db;


        }


        /// <summary>
        /// 系统授权
        /// </summary>
        /// <param name="HWKey">机器码</param>
        /// <param name="KeyCode">授权码</param>
        /// <returns></returns>
        public static string RegistSystem(string HWKey, string KeyCode)
        {
            SysJsonModel<object> json = new SysJsonModel<object>();
            json.Code = "200";
            json.Name = "系统注册";
            json.Msg = "注册成功";
            IFormatProvider provider = new CultureInfo("zh-CN", true);
            try
            {
                if (string.IsNullOrEmpty(HWKey))
                {
                    json.Code = "500";
                    json.Msg = "请输入机器码";
                }
                if (string.IsNullOrEmpty(KeyCode))
                {
                    json.Code = "500";
                    json.Msg = "请输入授权码";
                }
                string A0  = Security.DESDecrypt(KeyCode);
                string[] AS = A0.Split('|');
                if (AS.Length < 3)
                {
                    json.Code = "500";
                    json.Msg = "授权文件错误<授权信息错误>,联系软件厂商";
                  
                }
                if (!string.Equals(AS[0], HWKey))
                {
                    json.Code = "500";
                    json.Msg = "机器码与授权码无法对应,联系软件厂商";
                }

                string FilePath = System.Threading.Thread.GetDomain().SetupInformation.ConfigurationFile;
                ConfigHelper.SetAppSetttingValue(FilePath, "AU", KeyCode);

            }
            catch (Exception ex)
            {
                json.Code = "500";
                json.Msg = ex.ToString();
            }
            return JsonConvert.SerializeObject(json);
        }

        /// <summary>
        /// 获取授权码
        /// </summary>
        /// <param name="HWKey"></param>
        /// <returns></returns>
        public static string GetAuthorizationForerver(string HWKey)
        {

            return Security.DESEncrypt(HWKey + "|" + DateTime.Now.ToString("yyyyMMdd") + "|" + DateTime.Now.AddDays(100000).ToString("yyyyMMdd"));

           

        }
    }
}
